package com.xianyun.common.security.utils;

import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper;
import com.xianyun.common.core.exception.token.TokenDecryptException;
import com.xianyun.common.core.exception.token.TokenOverDueException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *  @author mac_zyj
 */
public class JwtUtil {

    private static final String EXP = "exp";

    private static final String PAYLOAD = "payload";

    /**
     * @Description 生成token,设置超时时间
     * @CreateTime 2020/08/06 9:47
     */
    public static <T> String sign(T object, long maxAge,String secret) throws IOException {
        final JWTSigner signer = new JWTSigner(secret);
        final Map<String, Object> claims = new HashMap<String, Object>(16);
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(object);
        claims.put(PAYLOAD, jsonString);
        claims.put(EXP, System.currentTimeMillis() + maxAge);
        return signer.sign(claims);
    }


    /**
     * @Description 解密token
     * @CreateTime 2020/08/06 9:47
     * @return  T
     */
    public static <T> T getTokenSignOut(String jwt, Class<T> classT,String secret) {
        try {
            final JWTVerifier verifier = new JWTVerifier(secret);
            final Map<String, Object> claims = verifier.verify(jwt);
            if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) {
                long exp = (Long) claims.get(EXP);
                long currentTimeMillis = System.currentTimeMillis();
                if (exp > currentTimeMillis) {
                    String json = (String) claims.get(PAYLOAD);
                    ObjectMapper objectMapper = new ObjectMapper();
                    return objectMapper.readValue(json, classT);
                }else {
                    //登录信息过期
                    throw  new TokenOverDueException();
                }
            }
            return null;
        } catch (Exception ignored){
            System.out.println(ignored.getMessage());
            throw new TokenDecryptException();
        }
    }
}

